package edu.jxufe.nb112.blog.core.persist.service.user;

import edu.jxufe.nb112.blog.core.constant.CacheConstant;
import edu.jxufe.nb112.blog.core.persist.entity.User;
import edu.jxufe.nb112.blog.core.persist.entity.UserAuth;
import edu.jxufe.nb112.blog.core.persist.mapper.UserAuthMapper;
import edu.jxufe.nb112.blog.core.persist.mapper.UserMapper;
import edu.jxufe.nb112.common.code.cache.CacheService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class.getName());

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserAuthMapper userAuthMapper;
    @Autowired
    CacheService cacheService;

    @Transactional
    public boolean register(User user, UserAuth userAuth) {
        if(StringUtils.isEmpty(user.getNickname())){
            user.setNickname(user.getAccount());
        }
        if(userMapper.insertUser(user)==1 && userAuthMapper.insertUserAuth(userAuth)==1){
            //清理注册页面账号查询缓存
            cacheService.evict(CacheConstant.ACCOUNT_CACHE,CacheConstant.ACCOUNT_CACHE_ACCOUNT_PREFIX+user.getAccount());
            cacheService.evict(CacheConstant.ACCOUNT_CACHE,CacheConstant.ACCOUNT_CACHE_EMAIL_PREFIX+user.getEmail());
            return true;
        }
        return false;
    }

    @Transactional(readOnly = true)
    public User findUserByAccount(String account) {
        return userMapper.findUserByAccount(account);
    }

    @Transactional(readOnly = true)
    public String findAccountByEmail(String email) {
        return userMapper.findAccountByEmail(email);
    }

    @Cacheable(value = CacheConstant.ACCOUNT_CACHE,key = "'"+CacheConstant.ACCOUNT_CACHE_ACCOUNT_PREFIX+"'+#account")
    @Transactional(readOnly = true)
    public boolean hasAccount(String account) {
        return userMapper.findUserCountByAccount(account)>0;
    }
    @Cacheable(value = CacheConstant.ACCOUNT_CACHE,key = "'"+CacheConstant.ACCOUNT_CACHE_EMAIL_PREFIX+"'+#email")
    @Transactional(readOnly = true)
    public boolean hasEmail(String email) {
        return userMapper.findUserCountByEmail(email)>0;
    }

}
